package com.wanlian.json;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.wanlian.util.DateUtil;
import com.wanlian.util.StringUtil;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;

public class MyTimestampDeserializer extends JsonDeserializer<Timestamp> {

    @Override
    public Timestamp deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        String value = p.getValueAsString();
        try {
            if (!StringUtil.hasValue(value)) {
                return null;
            }
            if (isNumber(value)) {
                if (value.length() == 10) {
                    value = String.format("%s000", value);
                }
                return new Timestamp(Long.valueOf(value));
            }
            Date srcDate = DateUtil.stringToDate("yyyy-MM-dd", value);
            value = DateUtil.dateToString("yyyy-MM-dd HH:mm:ss", srcDate);
            return Timestamp.valueOf(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private boolean isNumber(String str) {
        String reg = "^\\d+$";
        return str.matches(reg);

    }

}
